package de.herzog.bbp.view.javafx;

import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import de.herzog.bbp.model.dao.AbstractDAO;
import de.herzog.bbp.view.bean.AbstractBean;

public class SaveOnSelectionChangedListener<T extends AbstractBean> implements ListChangeListener<Integer> {

	private ObservableList<T> beanList;

	public SaveOnSelectionChangedListener(ObservableList<T> beanList) {
		this.beanList = beanList;
	}

	@Override
	public void onChanged(Change<? extends Integer> change) {
		while (change.next()) {
			for (Integer index : change.getRemoved()) {
				AbstractBean bean = beanList.get(index);
				bean.getDirtyModels().forEach(AbstractDAO::persist);
				bean.setDirty(false);
			}
		}
	}
}
